package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @projectName: sky-take-out
 * @package: com.sky.controller.admin
 * @className: CommonController
 * @author: Eric
 * @description: TODO
 * @date: 2025/3/21 19:42
 * @version: 1.0
 */

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口-文件上传")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public Result upload(MultipartFile file){
        log.info("文件上传:{}",file);
        String filename = file.getOriginalFilename();
        String extension =  filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + extension;
        String upload = null;
        try {
            upload = aliOssUtil.upload(file.getBytes(), newFileName);
        } catch (IOException e) {
            log.error("文件上传失败:{}",e.getMessage());
            e.printStackTrace();
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        return Result.success(upload);
    }
}
